package com.example.xx;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Barrettl
 * @description
 * @date 2022/2/15 15:40
 **/
public class ToSql02 {
    static Pattern fieldLine = Pattern.compile("\\w+\\s+[\\w|\\.]+\\s+\\w+;");
    static Pattern fieldProperty = Pattern.compile("\\w+;$");
    static Pattern humpPattern = Pattern.compile("[A-Z]");
    static Pattern tableLine = Pattern.compile("(?<=@Table\\s{0,5}\\()[^\\)]*");
    static Pattern clazzLine = Pattern.compile("(?<=public\\s{1,5}class\\s{1,5})\\w+");
    static String str = " ";

    public static void main(String[] args) {
        String perfix = "t1";
        String content = "@Table         (name = product_recommend, catalog = stellrprod)";
        System.out.println(matchhTableName(content));
//         mathTable0(content);
    }


    public static String process(String content, String prefix, String ignore, boolean selected) {
        prefix = prefix.trim();
        Set<String> ignoreSet = Arrays.stream(ignore.split(",")).map(String::trim).collect(Collectors.toSet());
        String tName = matchhTableName(content);
        StringBuffer sb = new StringBuffer();
        appendSelectIfNeed(selected, tName, sb);
        appendColumn(content, prefix, ignoreSet, sb);
        appendFromIfNeed(prefix, selected, tName, sb);
        return sb.toString();
    }

    private static void appendColumn(String content, String perfix, Set<String> ignoreSet, StringBuffer sb) {
        Matcher matcher = fieldLine.matcher(content);
        List<String> matchStrs = new ArrayList<>();
        while (matcher.find()) { //此处find（）每次被调用后，会偏移到下一个匹配
            matchStrs.add(matcher.group());//获取当前匹配的值
        }
        for (int i = 0; i < matchStrs.size(); i++) {
            String x = matchStrs.get(i);
            String group = getLast(x);
            String oStr = group.substring(0, group.length() - 1);
            if (ignoreSet.contains(oStr)) {
                continue;
            }
            humpToLine2(oStr, sb, perfix);
            sb.append(str);
            sb.append(" AS ");
            sb.append(str);
            sb.append(oStr);
            sb.append(" ,\n");
        }
        if (sb.length() > 0) {
            sb.delete(sb.length() - 2, sb.length());
            sb.append("\n");
        }
    }

    private static void appendFromIfNeed(String prefix, boolean selected, String tName, StringBuffer sb) {
        if (selected && tName != null) {
            sb.append("FROM \n").append(tName);
            if (prefix != null && !prefix.isEmpty()) {
                sb.append(" AS ");
                sb.append(prefix);
            }
        }
    }

    private static void appendSelectIfNeed(boolean selected, String tName, StringBuffer sb) {
        if (selected && tName != null) {
            sb.append("SELECT \n");
        }
    }

    private static String matchhTableName(String content) {
        Matcher matcher = tableLine.matcher(content);
        Map<String, String> map = new HashMap<>(2, 1);
        if (matcher.find()) {
            String group = matcher.group();
            String[] kv = group.replace('"',' ').split(",");
            for (String s : kv) {
                String[] split = s.split("=");
                map.put(split[0].trim(), split[1].trim());
            }
        } else {
            // using class
            Matcher mC = clazzLine.matcher(content);
            if (mC.find()) {
                StringBuffer sb = new StringBuffer();
                humpToLine2(mC.group().trim(), sb, "");
                map.put("name", sb.toString());
            }
        }
        String catalog = map.get("catalog");
        String name = map.get("name");
        if (name == null) {
            return null;
        }
        if (catalog == null || catalog.isEmpty()) {
            return name;
        }
        return catalog + "." + name;

    }

    private static String getLast(String x) {

        Matcher matcher = fieldProperty.matcher(x);
        while (matcher.find()) {
            return matcher.group(0);
        }
        throw new RuntimeException("Error: " + x);
    }

    /**
     * 驼峰转下划线,效率比上面高
     */
    public static void humpToLine2(String str, StringBuffer sb, String prefix) {
        Matcher matcher = humpPattern.matcher(str);
        int last = -1;
        while (matcher.find()) {
            int isx = matcher.start();
            if (last == -1 && !prefix.isEmpty()) {
                sb.append(prefix).append(".");
            }
            sb.append(str.substring(last + 1, isx));
            if (isx != 0) {
                // first Capital ignore
                sb.append("_");
            }
            sb.append(matcher.group().toLowerCase());
            last = isx;
        }
        if (last == -1 && !prefix.isEmpty()) {
            sb.append(prefix).append(".");
        }
        if (last != str.length()) sb.append(str.substring(last + 1));
    }
}
